/*
    Copyright 2007-2011 Patrik Jonsson, sunrise@familjenjonsson.org

    This file is part of Sunrise.

    Sunrise is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.

    Sunrise is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Sunrise.  If not, see <http://www.gnu.org/licenses/>.

*/

/// \file
/// Contains implementations and explicit instantiations of the
/// scatter_stage class. \ingroup mcrx

// $Id$

#include "config.h"
#include "mcrx-stage.h"
#include "mcrx-stage-impl.h"
#include "create_grid.h"
#include "arepo_grid.h"
#include "arepo_emission.h"

using namespace std;

template <template <typename> class grid_type> 
bool mcrx::scatter_stage<grid_type>::check_stage_state () const
{
  bool state = false;
  try {
    this->output_file_->pHDU().readKey("MCRX" + stage_ID(), state);
  }
  catch (...) {}
  return state;
}

template <template <typename> class grid_type> 
void mcrx::scatter_stage<grid_type>::set_stage_state (bool state)
{
  this->output_file_->pHDU().addKey("MCRX" + stage_ID(), state, "");
}

template <template <typename> class grid_type> 
void mcrx::scatter_stage<grid_type>::setup_objects ()
{
  // Build emission
  cout << "Setting up emission" << endl;
  CCfits::ExtHDU& pdata_hdu = open_HDU(*this->input_file_, "PARTICLEDATA");
  this->emi_.reset(new T_emission(pdata_hdu, 
				  this->p_.defined("use_reference_for_emission") &&
				  this->p_.getValue("use_reference_for_emission", bool()))
		   );

  // Set up dust model (this one is painful)
  cout << "Setting up dust model" << endl;
  // First read wavelength vector
  CCfits::ExtHDU& lambda_hdu = open_HDU (*this->output_file_, "LAMBDA");
  read(lambda_hdu.column("lambda"),lambda_);

  // Read dust grains
  typename T_dust_model::T_scatterer_vector sv
    (read_dust_grains<typename T_dust_model::T_scatterer_vector>(this->p_, this->m_.units));
  this->model_.reset(new T_dust_model (sv));
  this->model_->set_wavelength(lambda_);

  // Now build grid
  cout << "Building grid" << endl;

  // The density generator is used to generate the densities of the
  // dust grains from the gas and metal densities in the simulation.  
  uniform_density_generator dg(this->p_);
  //  const int lambda_subsample =
  //    this->p_.defined("intensity_subsampling") ?
  //    this->p_.getValue("intensity_subsampling", int()) : 1;

  // by definition, we don't track intensities in this stage, so we
  // can set n_lambda to zero to save memory here
  const int n_lambda = 0; 
  T_grid* dummy=0;
  this->g_ = create_grid(*this->input_file_, dg, n_lambda, dummy);

  // Build cameras based on -PARAMETERS HDUs in output file
  cout << "Setting up emergence" << endl;
  this->eme_.reset(new T_emergence (*this->output_file_));

  // if we are doing kinematic calculation, set the wavelength scale of the cameras
  if(this->p_.defined("use_kinematics") && 
     this->p_.getValue("use_kinematics", bool())) {
    typename T_emergence::iterator stop= this->eme_->end();
    for (typename T_emergence::iterator c = this->eme_->begin();
	 c != stop; ++c)
      (*c)->set_dopplerscale(lambda_);
  }

  typename T_emergence::iterator stop= this->eme_->end();
  for (typename T_emergence::iterator c = this->eme_->begin();
       c != stop; ++c) {
    (*c)->allocate(this->emi_->zero_lambda());
    assert((*c)->get_image().size()>0);
  }

  // find reference wavelength
  vector<T_float> templambda(lambda_.begin(), lambda_.end());
  reflambda_= 
    lower_bound (templambda.begin(), templambda.end(),
		 this->p_.getValue("reference_wavelength", T_float ())) -
    templambda.begin();
  assert(reflambda_>=0);
  assert(reflambda_<lambda_.size());

  cout << "Reference wavelength: " << lambda_ (reflambda_) << " ("
       << reflambda_<< ")\n";
}


template <template <typename> class grid_type> 
void mcrx::scatter_stage<grid_type>::load_file ()
{
  // first set up general stuff
  setup_objects();

  // Only thing to load is camera images
  this->eme_->load_images(*this->output_file_, "");
}


template <template <typename> class grid_type> 
void mcrx::scatter_stage<grid_type>::load_dump (binifstream& dump_file)
{
  // first set up general stuff
  setup_objects();

  // Only thing to load is camera images
  this->eme_->load_dump(dump_file);
}


template <template <typename> class grid_type> 
void mcrx::scatter_stage<grid_type>::save_file ()
{
  // Get normalization and save images
  const T_float normalization = 1./this->n_rays_;
  this->eme_->write_images(*this->output_file_, normalization, this->m_.units,
			   "",
			   this->p_.defined("compress_images")&&
			   this->p_.getValue("compress_images", bool ()),
			   this->p_.defined("write_images_parallel")&&
			   this->p_.getValue("write_images_parallel", bool ()));
}


template <template <typename> class grid_type> 
void mcrx::scatter_stage<grid_type>::save_dump (binofstream& dump_file) const
{
  this->eme_->write_dump(dump_file);
}


template <template <typename> class grid_type> 
bool mcrx::scatter_stage<grid_type>::shoot ()
{
  this->m_.mon_.set_images(*this->eme_, reflambda_);

  bool r= this->shoot_scatter (false);
  this->m_.mon_.clear_images();

  return r;
}

template <template <typename> class grid_type> 
void mcrx::scatter_stage<grid_type>::operator() ()
{
  // this is here so the function is instantiated
  this->run_stage();
}


// explicit instantiations
template class mcrx::scatter_stage<mcrx::adaptive_grid>;

#ifdef WITH_AREPO
template class mcrx::scatter_stage<mcrx::arepo_grid>;
#endif
